package com.android.duininsuoai.activity.mine;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.duininsuoai.R;
import com.android.duininsuoai.app.BaseActivity;
import com.android.duininsuoai.model.member.LoginResultData;
import com.android.duininsuoai.model.member.LoginResultDataCallback;
import com.android.duininsuoai.model.member.SendCodeData;
import com.android.duininsuoai.model.member.SendCodeDataCallback;
import com.android.duininsuoai.utils.ConstantsUrl;
import com.android.duininsuoai.utils.HttpUtils;
import com.android.duininsuoai.utils.MyLog;
import com.android.duininsuoai.utils.ObjectUtils;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


public class SignActivity extends BaseActivity {


    @BindView(R.id.main_top_back)
    ImageView back;
    @BindView(R.id.ll_sign_phone)
    EditText llSignPhone;
    @BindView(R.id.ll_sign_code)
    EditText llSignCode;
    @BindView(R.id.ll_sign_code_send)
    TextView llSignCodeSend;
    @BindView(R.id.ll_sign_pd)
    EditText llSignPd;
    @BindView(R.id.ll_sign_inviter)
    EditText Inviter;
    @BindView(R.id.main_top_login)
    TextView main_top_login;
    @BindView(R.id.register)
    TextView register;

    private boolean networkConnected;
    private TimeCount time;
    private String openid;
    private String type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign);
        ButterKnife.bind(this);
        openid = getIntent().getStringExtra("openid");
        type = getIntent().getStringExtra("type");
        initUI();
        time = new TimeCount(60000, 1000);
    }

    private boolean isCheck = true;

    private void initUI() {

    }

    //登录
    private void PostLogin(String phone, String pd) {
        networkConnected = ObjectUtils.isNetworkConnected(this);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORLOGIN;
        HashMap<String, String> map = new HashMap<>();
        MyLog.e("地址", address);
        map.put("username", phone);
        map.put("password", pd);
        if (networkConnected) {
            HttpUtils.post(address, map, new LoginResultDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                }

                @Override
                public void onResponse(LoginResultData response, int id) {
                    if (response.getCode() == 0) {
                        //保存用户数据
                        PostLoginThree(response.getData().getUNAME(), response.getData().getAvatar(), response.getData().getUID(), response.getData().getUPSW());
                    } else {
                        ObjectUtils.toast(SignActivity.this, response.getMsg());
                    }

                }
            });

        } else {

            ObjectUtils.toast(this, "网络连接出错了");
        }

    }

    private void PostSign(String phone, String code, String pd) {
        networkConnected = ObjectUtils.isNetworkConnected(this);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORSIGN;
        MyLog.e("地址", address);
        if (networkConnected) {
            HashMap<String, String> map = new HashMap<>();
            map.put("mobile", phone);
            map.put("verifycode", code);
            map.put("password", pd);
            String inviterID = Inviter.getText().toString();
            map.put("inviter_id", inviterID);
            if(!TextUtils.isEmpty(type)){
                map.put("openid", openid);
                map.put("type", type);
            }
            HttpUtils.post(address, map, new LoginResultDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {

                }

                @Override
                public void onResponse(LoginResultData response, int id) {
                    if (response.getCode() == 0) {
                        //保存用户数据
                        if(!TextUtils.isEmpty(type)){
                            setResult(1);
                            finish();
                        }else {
                            PostLoginTwo(response.getData().getUNAME(), response.getData().getAvatar(), response.getData().getUID(), response.getData().getUPSW());
                        }
                    } else {
                        ObjectUtils.toast(SignActivity.this, response.getMsg());
                    }

                }
            });

        } else {

            ObjectUtils.toast(this, "网络连接出错了");
        }

    }


    //发送验证码
    private void SendCode(String phone) {
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORSENDMESSAGE;
        HashMap<String, String> map = new HashMap<>();
        map.put("mobile", phone);
        map.put("act", "sms_register");
        networkConnected = ObjectUtils.isNetworkConnected(this);
        if (networkConnected) {

            HttpUtils.post(address, map, new SendCodeDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {

                }

                @Override
                public void onResponse(SendCodeData response, int id) {

                    ObjectUtils.toast(SignActivity.this, response.getMsg());
                    if (response.getCode() == 0) {
                        time.start();
                    }

                }
            });

        } else {

            ObjectUtils.toast(this, "网络连接出错了");
        }

    }


    @OnClick({R.id.main_top_back, R.id.ll_sign_code_send, R.id.register, R.id.main_top_login,})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id. main_top_login:
                Intent loginintent = new Intent(this,LoginActivity.class);
                loginintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(loginintent);
                finish();
                break;
            case R.id.main_top_back:
                finish();
                break;
            case R.id.ll_sign_code_send:
                String sign_phone = llSignPhone.getText().toString().trim();
                if ("".equals(sign_phone)) {
                    ObjectUtils.toast(this, "请输入手机号码");
                    return;
                }
                SendCode(sign_phone);
                break;
            case R.id.register:
//                if (isCheck) {
//                    String lgphone = llLoginPhone.getText().toString().trim();
//                    String lgpd = llLoginPd.getText().toString().trim();
//                    if ("".equals(lgphone)) {
//                        ObjectUtils.toast(this, "请输入账号");
//                        return;
//                    }
//                    if ("".equals(lgpd)) {
//                        ObjectUtils.toast(this, "请输入密码");
//                        return;
//                    }
//
//
//                } else {
                    String sgphone = llSignPhone.getText().toString().trim();
                    String sgcode = llSignCode.getText().toString().trim();
                String lgpd = llSignPd.getText().toString().trim();
                    if ("".equals(sgphone)) {
                        ObjectUtils.toast(this, "请输入手机号");
                        return;
                    }
                    if ("".equals(sgcode)) {
                        ObjectUtils.toast(this, "请输入验证码");
                        return;
                    }
                  if ("".equals(lgpd)) {
                        ObjectUtils.toast(this, "请输入密码");
                        return;
                    }
                PostSign(sgphone,sgcode,lgpd);
            //    }

                break;
        }
    }

    //登录并保存
    private void PostLoginThree(String uname, String avatar, String uid, String upsw) {
        SharedPreferences sp = getSharedPreferences(ConstantsUrl.USERDATA, 0);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(ConstantsUrl.USERDATA_NAME, uname);
        edit.putString(ConstantsUrl.USERDATA_AVATAR, avatar);
        edit.putString(ConstantsUrl.USERDATA_UID, uid);
        edit.putString(ConstantsUrl.USERDATA_UPSW, upsw);
        edit.putInt(ConstantsUrl.USERDATA_TYPE, 0);
        edit.commit();
        ObjectUtils.toast(SignActivity.this, "登录成功");
        LoginActivity.intance.finish();
        finish();
    }
    //注册并保存
    private void PostLoginTwo(String uname, String avatar, String uid, String upsw) {
        SharedPreferences sp = getSharedPreferences(ConstantsUrl.USERDATA, 0);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(ConstantsUrl.USERDATA_NAME, uname);
        edit.putString(ConstantsUrl.USERDATA_AVATAR, avatar);
        edit.putString(ConstantsUrl.USERDATA_UID, uid);
        edit.putString(ConstantsUrl.USERDATA_UPSW, upsw);
        edit.putInt(ConstantsUrl.USERDATA_TYPE, 0);
        edit.commit();
        ObjectUtils.toast(SignActivity.this, "注册成功");
       // SignActivity.finish();
        finish();
    }
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            llSignCodeSend.setText("重新获取验证码");
            llSignCodeSend.setTextColor(Color.parseColor("#ffffff"));
            llSignCodeSend.setBackgroundResource(R.drawable.corner_red_bg);
            llSignCodeSend.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            llSignCodeSend.setClickable(false);// 防止重复点击
            llSignCodeSend.setTextColor(Color.parseColor("#5a5a5a"));
            llSignCodeSend.setBackgroundResource(R.drawable.corner_gray_bg);
            llSignCodeSend.setText("重新发送(" + millisUntilFinished / 1000 + ")秒");
        }
    }
}
